package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.entity.result.Result;
import com.hmdp.entity.vo.UserVo;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.BaseContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.constant.RedisConstants.FOLLOW_KEY_PREFIX;

/**
 * 用户关注Service实现类
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 根据isFollow判断是关注还是取关，如果关注则插入数据，否则删除数据
     * @param followUserId 被关注的用户id
     * @param isFollow 关注true/取关false
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 获取当前登录用户id
        Long userId = ((UserVo) BaseContext.get()).getId();
        // 判断是关注还是取关
        if (isFollow) {
            // 关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                // 把关注用户的id放入Redis的Set集合 sadd userId followUserId
                stringRedisTemplate.opsForSet().add(FOLLOW_KEY_PREFIX + userId, followUserId.toString());
            }
        }else {
            // 取关，删除数据 delete from tb_follow where user_id = ? and follow_user_id = ?
            boolean isSuccess = remove(new LambdaQueryWrapper<Follow>()
                    .eq(Follow::getUserId, userId)
                    .eq(Follow::getFollowUserId, followUserId));
            if (isSuccess) {
                // 把关注用户的id从Redis集合中移除
                stringRedisTemplate.opsForSet().remove(FOLLOW_KEY_PREFIX + userId, followUserId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 判断当前登录用户是否关注了指定用户
     * @param followUserId 被关注的用户id
     * @return 是否关注，true关注，false未关注
     */
    @Override
    public Result isFollow(Long followUserId) {
        // 获取当前登录用户id
        Long userId = ((UserVo) BaseContext.get()).getId();
        // 查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
        Long count = lambdaQuery()
                .eq(Follow::getUserId, userId)
                .eq(Follow::getFollowUserId, followUserId)
                .count();
        // 判断是否关注
        return Result.ok(count > 0);
    }

    /**
     * 查询目标用户的共同关注
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        // 获取当前用户
        Long userId = ((UserVo) BaseContext.get()).getId();
        String key = FOLLOW_KEY_PREFIX + userId;
        // 求交集
        String targetKey = FOLLOW_KEY_PREFIX + id;
        Set<String> intersection = stringRedisTemplate.opsForSet().intersect(key, targetKey);
        if (CollUtil.isEmpty(intersection)) {
            // 无交集
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = intersection.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserVo> userVoList = userService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserVo.class))
                .collect(Collectors.toList());
        return Result.ok(userVoList);
    }
}
